#include <stdlib.h>
#include "common.h"

List* ListCreate()
{
	//Allocate memory the list structure
	List* pList = (List*)malloc(sizeof(List));

	//Initialize it's members.
	pList->first = null;
	pList->last = null;
	pList->size = 0;

	//Return the list.
	return pList;
}

void ListFree(List* pList, FreeObject* fFree)
{
	//NOTE: it is up to the caller to insure list members have been freed.
	//Free all the list items.
	ListItem* pItem = pList->first;
	ListItem* pItemTemp;

	while (pItem != null)
	{
		pItemTemp = pItem->next;
		if (fFree != null) fFree(pItem->value);
		free(pItem);
		pItem = pItemTemp;
	}

	//Free the list.
	free(pList);
}

void* ListAdd(List* pList, void* pObject)
{
	//Create a new list item and initialize it.
	ListItem* pItem = (ListItem*)malloc(sizeof(ListItem));
	pItem->next = null;
	pItem->prevoius = pList->last;
	pItem->value = pObject;

	//Incroment the list isze and add the item to the list.
	pList->size++;

	//If the list is empty then add it to the top.
	if (pList->first == null)
	{
		pList->first = pItem;
		pList->last = pItem;
	}
	//Otherwise add the new item to the bottom of the list.
	else
	{
		pList->last->next = pItem;
		pList->last = pItem;
	}

	return pObject;
}
